<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm" style="z-index: 2000">
      <el-row>
        <el-row v-if="form.showHistoryBtn !== undefined && parseInt(form.showHistoryBtn) > 0" :span="24">
          <div style="float: right;margin-right: 30px;margin-bottom: -10px;">
            <el-button
              type="warning"
              size="mini"
              @click="comparisonData()"
            >{{ $t('比对数据') }}</el-button>
          </div>
        </el-row>
        <el-col :span="24">
          <el-form-item :label="$t('制度名称')" prop="systemName">
            <el-input v-model="form.systemName" :placeholder="$t('制度名称')" show-word-limit maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('部门')" prop="departmentId">
            <DeptSelect v-model="form.departmentId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('制度创建时间')" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('制度创建时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('制度生效时间')" prop="effectTime">
            <el-date-picker
              v-model="form.effectTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('制度生效时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('制度类型')" prop="systemType">
            <el-select v-model="form.systemType" value="" :placeholder="$t('制度类型')">
              <el-option
                v-for="dict in systemTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('制度级别')" prop="systemLevel">
            <el-select v-model="form.systemLevel" value="" :placeholder="$t('制度级别')">
              <el-option
                v-for="dict in systemLevelOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('参与讨论人员')" prop="partakeUser">
            <UserSelect v-model="form.partakeUser" :multiple="true" :placeholder="$t('参与讨论人员')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('制度简介')" prop="introduction">
            <el-input v-model="form.introduction" type="textarea" :placeholder="$t('制度简介')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--文件-->
      <FileTable :list.sync="form.fileList" data-type="oa_systemMake" :btn-show="!otherBtnHide || changeBtnStatus" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <div>
        <FormBtn ref="formBtn" :bus-data="form" :btn-hide="btnHide" has-permi="deal:contract" :menu-key="menuKey" :style="{ 'float': 'left', 'marginRight': changeBtnStatus ? '15px': '0' }" />
        <el-button
          v-if="changeBtnStatus"
          @click="cancel()"
        >{{ $t("取消") }}</el-button>
        <el-button
          v-if="changeBtnStatus"
          v-hasPermi="['deal:contract:edit']"
          type="primary"
          @click="submitForm('changeContract')"
        >{{ $t("变更并启动流程") }}</el-button>
      </div>
    </div>

    <!-- 对比页面 -->
    <el-dialog :title="$t('变更对比')" :visible.sync="oaSystemMakeComparedOpen" width="99%" top="1%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
      <oaSystemMakeCompared ref="oaSystemMakeCompared" />
    </el-dialog>
  </div>
</template>

<script>
import { saveOaSystemMake, getOaSystemMake, change, getOaSystemMake3 } from '@/api/oa/systemMake/oaSystemMake'
import { getUserProfile } from '@/api/system/user'
import oaSystemMakeCompared from '@/views/oa/systemMake/oaSystemMakeCompared.vue'
export default {
  components: {
    oaSystemMakeCompared
  },
  data() {
    return {
      oaSystemMakeComparedOpen: false,
      otherBtnHide: false,
      // 是否隐藏保存按钮
      btnHide: false,
      // 菜单标识
      menuKey: 'oa_systemMake',
      // 表单参数
      form: {
        fileList: []
      },
      oldOaSystemMake: undefined,
      systemTypeOptions: [],
      systemLevelOptions: [],
      // 变更重启流程按钮
      changeBtnStatus: false,
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        systemName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        userId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        departmentId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        startTime: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        systemType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        systemLevel: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
        // partakeUser: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      }
    }
  },
  created() {
    this.$bus.$emit('async_done')
    this.getDicts('system_type').then(response => {
      this.systemTypeOptions = response.data
    })
    this.getDicts('system_level').then(response => {
      this.systemLevelOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.changeBtnStatus = false
      this.initForm(data)
    },
    initForm(data) {
      var _this = this
      if (data != null && data.id !== undefined) {
        _this.loading = true
        getOaSystemMake(data.id).then(response => {
          _this.form = response.data
          _this.oldOaSystemMake = JSON.parse(JSON.stringify(_this.form))
          if (_this.oldOaSystemMake.fileList !== undefined && _this.oldOaSystemMake.fileList !== null && _this.oldOaSystemMake.fileList.length > 0) {
            _this.oldOaSystemMake.fileList.forEach(item => {
              item.id = undefined
              item.dataId = undefined
            })
          }
          _this.loading = false
        })
      } else {
        _this.loading = true
        _this.reset()
        getUserProfile().then(response => {
          _this.form.userId = response.data.id
          _this.form.departmentId = response.data.dept.id
          _this.loading = false
        })
      }
    },
    historyInit(data) {
      if (data != null && data.id !== undefined) {
        this.loading = true
        getOaSystemMake3(data.id).then(response => {
          this.form = response.data
          this.oldOaSystemMake = JSON.parse(JSON.stringify(this.form))
          this.loading = false
        })
      } else {
        this.msgError(this.$t('未能获取到信息'))
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        systemName: undefined,
        userId: this.$store.state.user.userId,
        departmentId: this.$store.state.user.deptId,
        startTime: new Date(),
        effectTime: undefined,
        systemType: undefined,
        systemLevel: undefined,
        partakeUser: undefined,
        introduction: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        showHistoryBtn: undefined,
        fileList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            if (type === 'changeContract') {
              this.startProcess({ id: this.form.id, type: 'changeContract' })
              resolve()
            } else {
              this.form.actTitle = this.form.systemName
              saveOaSystemMake(this.form).then(response => {
                if (response.code === 200) {
                  if (type === 'process') {
                    // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                    this.form.id = response.data
                    // 启动流程
                    this.startProcess(response.data)
                  } else {
                    this.msgSuccess(this.$t('保存成功'))
                    this.closeForm()
                    resolve()
                  }
                } else {
                  this.msgError(response.msg)
                }
                this.loading = false
              }).catch(() => {
                this.loading = false
                reject()
              })
            }
          } else {
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(data) {
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.systemName
      // 业务表名
      processData.dataTable = 'oa_system_make'
      // 业务ID
      processData.dataId = data.id
      // 业务表单地址
      processData.formPath = '@/views/oa/systemMake/oaSystemMakeForm'
      // 业务表单打印地址
      processData.viewPath = '@/views/oa/systemMake/oaSystemMakeView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      if (data.type === 'changeContract') {
        processData.onBeforeProcess = true
        this.form.oldOaSystemMake = this.oldOaSystemMake
        processData.form = this.form
      }
      this.loading = false
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 启动流程前保存数据
    onExtraProcessStart(data) {
      return new Promise((resolve, reject) => {
        var form = data.processData.form
        change(form).then(response => {
          if (response.code === 200 && response.msg !== '变更时发生异常!') {
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // 比对
    comparisonData() {
      this.oaSystemMakeComparedOpen = true
      this.$nextTick(() => {
        this.$refs.oaSystemMakeCompared.init(this.form)
      })
    }

  }

}
</script>
